package com.zhiyun.hxzy.service;

import com.zhiyun.hxzy.dao.DictionaryDao;
import com.zhiyun.hxzy.domain.Dictionary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class DictionaryService {
    @Autowired
    private DictionaryDao dictionaryDao;

    public Page<Dictionary> findAllDictionary(int pageNum, int pageSize, String type) {
        Specification specification = null;
        if (type != null) {
            specification = new Specification() {
                @Override
                public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                    Path type1 = root.get("type");
                    List<Predicate> list = new ArrayList<>();
                    list.add(criteriaBuilder.equal(type1, type));
                   Predicate p4 = criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
                   return p4;
                }
            };
        }

        if (pageNum < 0) {
            pageNum = 0;
        }

        PageRequest of = PageRequest.of(pageNum, pageSize, Sort.Direction.DESC,"type");

        Page all = dictionaryDao.findAll(specification, of);

        if (all.getTotalElements() <= 0) {
            Page<Dictionary> all2 = dictionaryDao.findAll(of);
            return all2;
        } else {
            return all;
        }
    }

    public List<Dictionary> typeDictionary(String type) {
        return dictionaryDao.findByType(type);
    }

    public void addDictionary(Dictionary dictionary) {
        dictionaryDao.save(dictionary);
    }

    public void deleteDictionary(Long[] ids) {
        for (Long idss : ids) {
            dictionaryDao.deleteById(idss);
        }
    }

    public Dictionary findByIdDictionary(Long id) {
        return dictionaryDao.findById(id).get();
    }

    public void updateDictionary(Dictionary dictionary) {
        dictionaryDao.save(dictionary);
    }

    public Page<Dictionary> likeDictionary(int pageNum, int pageSize, String type) {
        if (pageNum < 0) {
            pageNum = 0;
        }
        PageRequest of = PageRequest.of(pageNum, pageSize);
        return dictionaryDao.findByTypeLike(of, type);
    }

}
